package com.xf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xf.common.core.entity.CurrentUser;
import com.xf.common.core.entity.QueryRequest;
import com.xf.common.core.entity.constant.FebsConstant;
import com.xf.common.core.entity.constant.StringConstant;
import com.xf.common.core.entity.system.SystemUser;
import com.xf.common.core.entity.system.UserRole;
import com.xf.common.core.exception.FebsException;
import com.xf.common.core.utils.FebsUtil;
import com.xf.common.core.utils.SortUtil;
import com.xf.service.IUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.xf.common.core.entity.dmp.DmpAuthUser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.xf.mapper.DmpAuthUserMapper;
import com.xf.service.DmpAuthUserService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author JoeyLiu
 * @create 2022-04-01 13:59
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class DmpAuthUserServiceImpl extends ServiceImpl<DmpAuthUserMapper, DmpAuthUser> implements DmpAuthUserService {

    @Resource
    private  IUserRoleService userRoleService;
    @Resource
    private PasswordEncoder passwordEncoder;

    public DmpAuthUserServiceImpl() {
    }

    @Override
    public DmpAuthUser findByName(String username) {
        LambdaQueryWrapper<DmpAuthUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DmpAuthUser::getUserName, username);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<DmpAuthUser> findUserDetailList(DmpAuthUser user, QueryRequest request) {
        Page<DmpAuthUser> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "userId", FebsConstant.ORDER_ASC, false);
        return this.baseMapper.findUserDetailPage(page, user);
    }

    @Override
    public DmpAuthUser findUserDetail(String username) {
        DmpAuthUser param = new DmpAuthUser();
        param.setUserName(username);
        List<DmpAuthUser> users = this.baseMapper.findUserDetail(param);
        return CollectionUtils.isNotEmpty(users) ? users.get(0) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginTime(String username) {
        DmpAuthUser user = new DmpAuthUser();
//        user.setLastSigninTime(new Date());

        this.baseMapper.update(user, new LambdaQueryWrapper<DmpAuthUser>().eq(DmpAuthUser::getUserName, username));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUser(DmpAuthUser user) {
        // 创建用户
        user.setCreatedDate(new Date());
        user.setIcon(SystemUser.DEFAULT_AVATAR);
        user.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
        save(user);
        // 保存用户角色
        String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
        setUserRoles(user, roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(DmpAuthUser user) {
        // 更新用户
        user.setPassword(null);
        user.setUserName(null);
        user.setCreatedDate(null);
        user.setUpdatedDate(new Date());
        updateById(user);

        String[] userIds = {String.valueOf(user.getUserCode())};
        userRoleService.deleteUserRolesByUserId(userIds);
        String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
        setUserRoles(user, roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(String[] userIds) {
        List<String> list = Arrays.asList(userIds);
        removeByIds(list);
        // 删除用户角色
        this.userRoleService.deleteUserRolesByUserId(userIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProfile(DmpAuthUser user) throws FebsException {
        user.setPassword(null);
        user.setUserName(null);
        user.setStatus(null);
        if (isCurrentUser(user.getId())) {
            updateById(user);
        } else {
            throw new FebsException("您无权修改别人的账号信息！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAvatar(String avatar) {
        DmpAuthUser user = new DmpAuthUser();
        user.setIcon(avatar);
        String currentUsername = FebsUtil.getCurrentUsername();
        this.baseMapper.update(user, new LambdaQueryWrapper<DmpAuthUser>().eq(DmpAuthUser::getUserName, currentUsername));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(String password) {
        DmpAuthUser user = new DmpAuthUser();
        user.setPassword(passwordEncoder.encode(password));
        String currentUsername = FebsUtil.getCurrentUsername();
        this.baseMapper.update(user, new LambdaQueryWrapper<DmpAuthUser>().eq(DmpAuthUser::getUserName, currentUsername));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(String[] usernames) {
        DmpAuthUser params = new DmpAuthUser();
        params.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
        List<String> list = Arrays.asList(usernames);
        this.baseMapper.update(params, new LambdaQueryWrapper<DmpAuthUser>().in(DmpAuthUser::getUserName, list));

    }

    private void setUserRoles(DmpAuthUser user, String[] roles) {
        List<UserRole> userRoles = new ArrayList<>();
        Arrays.stream(roles).forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Long.valueOf(roleId));
            userRoles.add(userRole);
        });
        userRoleService.saveBatch(userRoles);
    }


    private boolean isCurrentUser(Long id) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        return currentUser != null && id.equals(currentUser.getUserId());
    }

}
